package com.sgcc.modules.monitor.notify;

import com.sgcc.common.redis.service.RedisService;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.notify.AbstractEventNotifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.concurrent.TimeUnit;


public class CustomNotifier extends AbstractEventNotifier {

    private static final Logger log = LoggerFactory.getLogger(CustomNotifier.class);

    private static final String NOTIFY_KEY = "NOTIFY_KEY";

    @Autowired
    private RedisService redisService;

    public CustomNotifier(InstanceRepository repository) {
        super(repository);
    }

    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        String serviceName = instance.getRegistration().getName();
        String serviceUrl = instance.getRegistration().getServiceUrl();
        String status = instance.getStatusInfo().getStatus();// UP、DOWN、UNKNOWN、OFFLINE
//        System.out.println(redisService == null);
        if("UP".equals(status) || "OFFLINE".equals(status)){
            //上线 or 下线
            redisService.setCacheObject(NOTIFY_KEY, System.currentTimeMillis(),180L, TimeUnit.DAYS);
        }
        return Mono.fromRunnable(() -> {
            log.info("服务预警:{},服务地址:{},状态:{}",serviceName,serviceUrl,status);
        });
    }
}
